package com.shz.appletsapi.service.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.shz.appletsapi.common.image.DownloadImage;
import com.shz.appletsapi.repository.GameRepository;

import lombok.extern.slf4j.Slf4j;


@Component
@Slf4j
@Profile(value = "download")
public class DownloadService {
	
	@Autowired
	private GameRepository gameRepository;
	private static final String  url="https://games.shzxcx.com/games/static/image/";

	//@Scheduled(initialDelay = 10000, fixedRate = 1000 * 60 * 60 * 4)
	public void download() {
		 Long startTime=new Date().getTime();
		 log.info("Download Starting ---------------------------------");
		List<Map<String,String>> urls =new ArrayList<>();
		gameRepository.findByIdent(0).forEach(s ->{
			Map<String,String> url =new HashMap<>();
			String imageUrl=s.getImageUrl();
			String wxQrCode=s.getWxQrCode();
			String[] screenshots = s.getScreenshots().split(",");
			url.put(s.getId()+"_imageUrl"+".jpg", imageUrl);
			url.put(s.getId()+"_wxQrCode"+".jpg", wxQrCode);
			if(screenshots != null && screenshots.length > 0) {
				for(int i =0; i<screenshots.length;i++) {
					url.put(s.getId()+"_screenshot"+(i+1)+".jpg", screenshots[i]);
				}
			}
			urls.add(url);
		});
		urls.stream().forEach(x -> {
			for (Map.Entry<String, String> entry : x.entrySet()) {
				try {
					DownloadImage.download(entry.getValue(), entry.getKey(),"./static/image/");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		 log.info("Download End ---------------------------------time:"+(new Date().getTime()-startTime));
	}
	
	
	
	//@Scheduled(initialDelay = 10000, fixedRate = 1000 * 60 * 60 * 4)
	public void saveFileUrl() {
		 log.info("saveFileUrl Starting ---------------------------------");
		gameRepository.findByIdent(1).forEach(s ->{
			
			String imageUrl=s.getImageUrl();
			String wxQrCode=s.getWxQrCode();
			String[] screenshots = s.getScreenshots().split(",");
			imageUrl=url+s.getId()+"_imageUrl"+".jpg";
			wxQrCode=url+s.getId()+"_wxQrCode"+".jpg";
			List<String> sc =new ArrayList<>();
			if(screenshots != null && screenshots.length > 0) {
				for(int i =0; i<screenshots.length;i++) {
					String screenshot=url+s.getId()+"_screenshot"+(i+1)+".jpg";
					sc.add(screenshot);
				}
			}
			s.setImageUrl(imageUrl);
			s.setWxQrCode(wxQrCode);
			s.setScreenshots(StringUtils.join(sc,","));
			gameRepository.save(s);
			log.info("save success "+s);
			
			
			
		});
		log.info("end Starting ---------------------------------");

}
}
